<?php


namespace App\Services;


use App\Models\User;
use App\Models\UserCollectRecruit;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;

class CollectService extends BaseService
{
    /**
     * 收藏招工
     * @param $input
     * @return array
     */
    public function collectRecruit($input)
    {
        $userId = $input['user_id'];
        $recruitId = $input['recruit_id'];
        $userCollectRecruit = UserCollectRecruit::query()->where(['user_id' => $userId, 'recruit_id' => $recruitId])->first();
        if (!is_null($userCollectRecruit)) {
            $collectId = $userCollectRecruit->id;
            $collectStatus = $userCollectRecruit->status == 1 ? 0 : 1;
            $userCollectRecruit->status = $collectStatus;
            $userCollectRecruit->save();
        } else {
            $collectId = UserCollectRecruit::query()->insertGetId(['user_id' => $userId, 'recruit_id' => $recruitId, 'status' => 1]);
            $collectStatus = 1;
        }
        return [
            'collect_id'   => $collectId,
            'is_collected' => $collectStatus
        ];
    }

    public function collectRecruitList(array $input, int $page, int $limit, string $sortField, string $orderRule,
                                       array $userTableColumns = ['*'], array $verifyTableColumns = ['*'], array $recruitTableColumns = ['*'])
    {
        $userId = $input['user_id'];

       /* return User::query()
            ->find($userId)
            ->collectRecruits()
            ->orderBy('user_collect_recruit.updated_at', 'desc')
            ->with(['user' => function(BelongsTo $query) {
                $query->select('id', 'nickname', 'avatar');
            }, 'user.verifyInfo'=> function(HasOne $query) {
                $query->select('id', 'user_id', 'type');
            }])
            ->get(['recruit.id', 'recruit.city', 'recruit.recruit_desc', 'recruit.created_at', 'recruit.user_id']);*/

        $query = User::query()
            ->find($userId)
            ->collectRecruits()
            ->with(['user' => function(BelongsTo $query) use ($userTableColumns) {
                $query->select($userTableColumns);
            }, 'user.verifyInfo'=> function(HasOne $query) use ($verifyTableColumns) {
                $query->select($verifyTableColumns);
            }]);

        if (!empty($sortField) && !empty($orderRule)) {
            $query = $query->orderBy($sortField, $orderRule);
        }

        $paginator = $query->paginate($limit, $recruitTableColumns, 'page', $page);
        return $this->optimizationPaginate($paginator);
    }
}
